package Stack_Queue.queue.Impl;

import Stack_Queue.queue.Queue;

import java.util.NoSuchElementException;

public class MyQueue<E> implements Queue<E> {
    //链表的每个节点
    private class Node {
        E val;
        Node next;

        public Node(E val) {
            this.val = val;
        }
    }

    //当前队列的元素个数
    private int size;
    //当前队列的队首
    private Node head;
    //当前队列的队尾
    private Node tail;

    @Override
    public void offer(E val) {
        Node node = new Node(val);
        if (head == null) {
            //链表为空
            head = tail = node;
        } else {
            tail.next = node;
            tail = node;
        }
        size++;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            throw new NoSuchElementException("queue is empty!");
        }
        E val = head.val;
        Node node = head;
        head = head.next;
        //将原来的头节点脱钩
        node.next = null;
        size--;
        return val;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            throw new NoSuchElementException("queue is empty!");
        }
        return head.val;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("front-[");
        //链表遍历
        for (Node x = head; x != null; x = x.next) {
            sb.append(x.val);
            if (x.next != null){
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}
